<template xmlns="http://www.w3.org/1999/html">
<!--导航栏-->
  <div>
  <header class="header">
    <div class="header-logo">
      <span class="logo-text">校园圈</span>
    </div>
    <div class="header-search">
      <form @submit.prevent="handleSearch">
        <input type="text" v-model="searchKeyword" placeholder="请输入关键字"  @input="checkLength"/>
        <button type="submit">搜索</button>
      </form>
    </div>
    <div class="my-account">
      <a href="#">我的</a>
    </div>
  </header>
  </div>
  <!--帖子-->
      <div class="page-container">
        <el-row :gutter="20">
          <!-- 左侧: 页面信息 -->
          <el-col :span="6">
            <div class="page-info">
              <el-row :gutter="20">
                <el-col :span="8">
                  <el-card shadow="never" class="profile-card">
                    <image-preview  :src="avatarSrc" alt="avatar" class="avatar-img"  :width="80" :height="80"/>
                  </el-card>
                </el-col>
                <el-col :span="16">
                  <el-form label-width="50px" class="form">
                    <el-form-item label="账号">
                      <el-input v-model="username" disabled />
                    </el-form-item>
                    <el-form-item label="爱好">
                      <el-select v-model="selectedInterest" placeholder="请选择">
                        <el-option
                            v-for="interest in interests"
                            :key="interest.value"
                            :label="interest.label"
                            :value="interest.value">
                        </el-option>
                      </el-select>
                    </el-form-item>
                  </el-form>
                </el-col>
              </el-row>

              <!-- 按钮区域 -->
              <div class="button-area">
                <el-button  type="primary" class="sign-in-btn"  icon="Plus" @click="handleAdd" v-hasPermi="['PostBarManger:PostBarManger:add']" >发布帖子</el-button>
              </div>

              <!-- 游戏推荐区域 -->
              <el-card class="game-recommendation">
                <template #header>
                  <h3>我的游戏</h3>
                </template>
                <p>热玩游戏榜，寻找你的她</p>
              </el-card>

              <!-- 精选专题区域 -->
              <el-card class="featured-topic">
                <template #header>
                  <h3>贴吧精选专题</h3>
                </template>
                <p>高校精选专题</p>
              </el-card>
            </div>
          </el-col>

          <!-- 中间: 朋友动态区域 -->
          <el-col :span="12">
            <div class="friends-feed">
              <div v-for="(post, index) in posts" :key="index" class="post">
                <div class="post-header">
                  <img :src="post.user.avatar" class="avatar" alt="Avatar">
                  <div class="user-info">
                    <h3 class="username">{{ post.user.name }}</h3>
                    <p class="timestamp">{{ post.timestamp }}</p>
                  </div>
                </div>
                <div class="post-content">
                  <a
                      :style="{ color: isHoveredType[index] ? 'blue' : 'black', textDecoration: isHoveredType[index] ? 'underline' : 'none' }"
                      @mouseover="handleMouseOverType(index)"
                      @mouseout="handleMouseOutType(index)"
                      @click ="handleClickType(index)"
                  >{{ post.type }}</a>
                  <p></p>
                  <a
                      @click="handleClickTitle(index)"
                      :style="{ color: isHoveredTitle[index] ? 'blue' : 'black', textDecoration: isHoveredTitle[index] ? 'underline' : 'none' }"
                      @mouseover="handleMouseOverTitle(index)"
                      @mouseout="handleMouseOutTitle(index)"
                  >{{ post.title }}</a>
                  <div class="post-text" v-html="post.text"></div>

                  <image-preview v-if="post.image" :src="post.image" alt="Post Image"/>
                </div>
                <div class="post-actions">
                  <div  :key="post.postId">
                    <button @click="toggleLike(index)">
                      <svg :class="{'liked': post.isLiked}" t="1722304884468" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="1497" width="20" height="20"><path d="M832 364.8h-147.2s19.2-64 32-179.2c6.4-57.6-38.4-115.2-102.4-121.6h-12.8c-51.2 0-83.2 32-102.4 76.8l-38.4 96c-32 64-57.6 102.4-76.8 115.2-25.6 12.8-121.6 12.8-128 12.8H128c-38.4 0-64 25.6-64 57.6v480c0 32 25.6 57.6 64 57.6h646.4c96 0 121.6-64 134.4-153.6l51.2-307.2c6.4-70.4-6.4-134.4-128-134.4z m-576 537.6H128V422.4h128v480z m640-409.6l-51.2 307.2c-12.8 57.6-12.8 102.4-76.8 102.4H320V422.4c44.8 0 70.4-6.4 89.6-19.2 32-12.8 64-64 108.8-147.2 25.6-64 38.4-96 44.8-102.4 6.4-19.2 19.2-32 44.8-32h6.4c32 0 44.8 32 44.8 51.2-12.8 102.4-32 166.4-32 166.4l-25.6 83.2h243.2c19.2 0 32 0 44.8 12.8 12.8 12.8 6.4 38.4 6.4 57.6z" p-id="1498">
                      </path></svg>
                    </button>

                  </div>
                </div>
              </div>
            </div>
          </el-col>
          <!-- 热搜帖子榜 -->
          <el-col :span="6">
            <div class="hot-posts">
              <h3>热搜帖子榜</h3>
              <div v-for="post in hotPosts" :key="post.id" class="post-item">
                <span class="post-index">{{ post.id }} </span>
                <span class="post-title">{{ post.title }}</span>
                <span class="post-popularity">🔥 {{ post.popularity }}</span>
              </div>
            </div>
          </el-col>
        </el-row>
      </div>


  <!-- 添加帖子动态管理对话框 -->
  <el-dialog :title="title" v-model="open" width="500px" append-to-body>
    <el-form ref="PostBarMangerRef" :model="form" :rules="rules" label-width="80px">
      <el-form-item label="发布账号" prop="userAccount">
        <el-input v-model="form.userAccount" placeholder="请输入发布账号" disabled />
      </el-form-item>
      <el-form-item label="用户昵称" prop="nickName">
        <el-input v-model="form.nickName" placeholder="请输入用户昵称" disabled />
      </el-form-item>
      <el-form-item label="帖子类别" prop="postType">
        <el-select v-model="form.postType" placeholder="请选择帖子类别">
          <el-option
              v-for="dict in post_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="帖子标题" prop="postTitle">
        <el-input v-model="form.postTitle" placeholder="请输入帖子标题" maxlength="15"  show-word-limit />
      </el-form-item>
      <el-form-item label="发布内容">
        <div class="editor-container" >
          <editor v-model="form.content"  :min-height="192"    />
        </div>
      </el-form-item>
      <el-form-item label="图片地址" prop="photo">
        <image-upload v-model="form.photo"/>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </template>
  </el-dialog>

</template>

<script setup>
import { ref } from 'vue';
//引入帖子数据
import { listPostBarManger, getPostBarManger, delPostBarManger, addPostBarManger, updatePostBarManger } from "@/api/PostBarManger/PostBarManger";
//引入用户信息
import { getUserProfile } from "@/api/system/user";
//引入点赞信息
import { addLikes} from "@/api/likes/likes";


const avatarSrc = ref();
const username = ref();
const userAccount1 = ref();
 getUserProfile().then(response => {
   username.value = response.data.userAccount;
   avatarSrc.value = response.data.avatar;
   userAccount1.value = response.data.phonenumber;
 })
const selectedInterest = ref('');
const interests = ref([
  { value: 'option1', label: '球赛' },
  { value: 'option2', label: '游戏' },
  { value: 'option3', label: '学习' }
]);


const { proxy } = getCurrentInstance();
const { post_type, sys_yes_no } = proxy.useDict('post_type', 'sys_yes_no');

const PostBarMangerList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
//处理时间
function formatRelativeTime(timestamp) {
  const now = new Date();
  const diff = now - timestamp;

  if (diff < 60 * 1000) {
    return '刚刚';
  } else if (diff < 120 * 1000) {
    return '1 分钟前';
  } else if (diff < 3600 * 1000) {
    return Math.floor(diff / (60 * 1000)) + ' 分钟前';
  } else if (diff < 7200 * 1000) {
    return '1 小时前';
  } else if (diff < 24 * 3600 * 1000) {
    return Math.floor(diff / (3600 * 1000)) + ' 小时前';
  } else if (diff < 48 * 3600 * 1000) {
    return '昨天';
  } else {
    return Math.floor(diff / (24 * 3600 * 1000)) + ' 天前';
  }
}

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    postId: null,
    userAccount: null,
    nickName: null,
    postType: null,
    postTitle: null,
    content: null,
    photo: null,
    publishDate: null,
    hot: null,
    delFlag: null
  },
  rules: {
    userAccount: [
      { required: true, message: "发布账号不能为空", trigger: "blur" }
    ],
    nickName: [
      { required: true, message: "用户昵称不能为空", trigger: "blur" }
    ],
    postType: [
      { required: true, message: "帖子类别不能为空", trigger: "blur" }
    ],
    postTitle: [
      { required: true, message: "帖子标题不能为空", trigger: "blur" },
      { max: 15, message: "帖子标题不能多于15个字符", trigger: "blur"}
    ],
    content: [
      { required: true, message: "帖子内容不能为空", trigger: "blur" },
      { max: 1000, message: "帖子内容不能多于1000个字符", trigger: "blur"}
    ]

  }
});
const { queryParams, form, rules } = toRefs(data);


//获取数据
const posts = ref([]);
const hotPosts = ref([])
function getList() {
  listPostBarManger(queryParams.value)
      .then(response => {
        const reversedRows = [...response.rows].reverse();
        //显示帖子
        posts.value = reversedRows.map(post => {
          const publishDate = new Date(post.publishDate);
          const relativeTime = formatRelativeTime(publishDate); // 假设你已经定义了formatRelativeTime函数

          return {
            postId: post.postId,
            user: {
              name: post.nickName,
              avatar: 'https://img1.baidu.com/it/u=193696007,2125345610&fm=253&app=120&size=w931&n=0&f=JPEG&fmt=auto?sec=1722013200&t=095d741d73979761af717338fd470eb1'
            },
            timestamp: relativeTime, // 使用相对时间替换原始时间字符串
            text: post.content,
            image: post.photo,
            likeCount: post.likeCount,
            hot: post.hot,
            type:post.postType,
            title: post.postTitle
          };
        });

        total.value = response.total;
      })
      .catch(error => {
        console.error("Failed to fetch list:", error);
      });
}




/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "发布帖子";
}

// 表单重置
function reset() {

  getUserProfile().then(response => {
    form.value.userAccount = response.data.phonenumber;
    form.value.nickName = response.data.nickName;
  })
  form.value = {
    postId: null,
    postType: null,
    postTitle: null,
    content: null,
    photo: null,
    publishDate: null,
    hot: null,
    delFlag: []
  };
  proxy.resetForm("PostBarMangerRef");
}
//取消按钮
function cancel() {
  open.value = false;
  reset();
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["PostBarMangerRef"].validate(valid => {
    if (valid) {
      form.value.delFlag = form.value.delFlag.join(",");
        addPostBarManger(form.value).then(response => {
          proxy.$modal.msgSuccess("发布成功");
          open.value = false;
          getList();
        });

    }
  });
}



const isHoveredType = ref([]);
const isHoveredTitle = ref([]);

onMounted(() => {
  // 初始化 isHoveredType 和 isHoveredTitle 数组
  for (let i = 0; i < posts.value.length; i++) {
    isHoveredType.value.push(false);
    isHoveredTitle.value.push(false);
  }
});

const handleMouseOverType = (index) => {
  isHoveredType.value[index] = true;
};

const handleMouseOutType = (index) => {
  isHoveredType.value[index] = false;
};

const handleMouseOverTitle = (index) => {
  isHoveredTitle.value[index] = true;
};

const handleMouseOutTitle = (index) => {
  isHoveredTitle.value[index] = false;
};


//获取gethotslist
function getHotList() {
  listPostBarManger()
      .then(response => {
        const reversedRows = [...response.rows].reverse();

        //根据帖子的热度及逆行排序并且只保留前15条数据
        let i = 1;
        hotPosts.value = reversedRows
            .map(post => ({
              title: post.postTitle,
              popularity: post.hot
            }))
            .sort((a, b) => b.popularity - a.popularity)
            .map((post, index) => ({ ...post, id: i++ }))
            .slice(0, 15);


        total.value = response.total;
      })
      .catch(error => {
        console.error("Failed to fetch list:", error);
      });
}



let isLiked = ref(false);

//点赞
const toggleLike = (index) => {
  addLikes({
    postId: posts.value[index].postId,
    userAccount:userAccount1.value,
    status: !posts.value[index].isLiked ? 1 : 0
  }).then(response => {
    if (response.code === 200) {
      posts.value[index].isLiked = !posts.value[index].isLiked;
      getHotList()
    }
  });


};

// 示例数据加载（在真实场景下，你可能从API获取数据）
onMounted(() => {
  // 这里可以调用API获取帖子数据并更新`posts`数组
});

// CSS样式
const styles = {
  liked: {
    fill: 'red'
  }
};

const searchKeyword = ref('');

const checkLength = () => {
  if (searchKeyword.value.length > 12) { // 假设最大长度为20
    searchKeyword.value = searchKeyword.value.slice(0, 12);
  }
};
const handleSearch = () => {
  console.log('搜索关键词:', searchKeyword.value);

  queryParams.value.pageNum = 1;
  queryParams.value.content = searchKeyword.value;
  getList();
  // 在这里添加你的搜索逻辑，例如调用API进行搜索
};

//获取帖子类别
function handleClickType(index) {
  queryParams.value.pageNum = 1;
  queryParams.value.postType = posts.value[index].type;
  getList();
  // 这里可以添加更多的逻辑，比如修改数据、导航到其他页面等
}
//查看帖子信息
function handleClickTitle(index){
  if (posts.value[index] && posts.value[index].title && posts.value[index].type) {
    window.location.href = `http://localhost/CampusCircle/CampusCircleSearch?title=${posts.value[index].title}&type=${posts.value[index].type}`;
  } else {
    console.error('Post data is missing or incomplete.');
  }}


getList();
getHotList();
</script>


<style scoped>


/*
 个人信息
*/
/* 基本样式 */
body {
  font-family: Arial, sans-serif;
}

/* 左侧用户信息样式 */
.page-info {
  margin-bottom: 20px;
  margin-left: 30px;
}
.profile-card {
  border: none;
}

.form {
  margin-top: 20px;
}

/* 按钮区域样式 */
.button-area {
  display: flex;
  justify-content: space-between;
  margin-top: 20px;
}
.sign-in-btn,
.add-interest-btn {
  flex: 1;
  margin-right: 10px;
}

/* 游戏推荐区域和精选专题区域样式 */
.game-recommendation,
.featured-topic {
  margin-top: 20px;
}


/*帖子样式*/
.friends-feed {
  max-width: 600px;
  margin: 0 auto;
  display: flex;
  flex-direction: column;
  gap: 1rem;
  padding: 1rem;
}

.post {
  background-color: #99a9bf;
  border-radius: 5px;
  padding: 1rem;
}

.post-header {
  display: flex;
  align-items: center;
}

.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  margin-right: 1rem;
}

.post-content img {
  max-width: 100%;
  height: auto;
}

.post-actions button {
  border: none;
  margin-right: 0.5rem;
  background-color: #99a9bf;
}


/*导航栏样式*/
.header {
  height: 80px;
  margin: 0 auto;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: white;
  padding: 10px 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); /* 阴影效果 */
}


.header-language a {
  color: #000000;
  text-decoration: none;
  margin-right: 10px;
}
.header-logo {
  color: #000000;
  font-size: xx-large;
  margin-left: 100px;
}
.header-search {
  margin-right: 50px;
  position: relative;
}

.header-search input {
  width: 500px;
  height: 50px;
  padding: 5px 10px;
  border: none;
  border-radius: 10px;
  background-color: #dddddd;
  color: #000000;
  font-size: 25px;
  outline: none;
  transition: all 0.3s ease;

}
.my-account {
  margin-right: 80px;
  color: #ffffff;
  font-size: 25px;
}

.header-search button {
  position: absolute;
  right: 0;
  top: 0;
  bottom: 0;
  background-color: transparent;
  border: none;
  color: #000000;
  font-size: 20px;
  cursor: pointer;
  padding: 5px 10px;

}
.header-menu {

  display: flex;
  justify-content: center; /* 水平居中 */
  gap: 5rem;


  font-size: 20px;
  font-weight: bold;
  color: #ffffff;
  align-items: center;
  padding: 20px 20px;
  background-color: #2c3e50;

}

.menu-item {
  text-decoration: none;
  font-size: 20px;
  margin-right: 20px;
  text-decoration: none;
  padding: 0.5rem 1rem;
  color: inherit;
}

.menu-item:hover {
  color: red;
}


/*热搜榜*/

.hot-posts {
  background-color:#99a9bf;
  width: 90%;
  border-radius: 5px;
  margin-top: 18px;
  padding-left: 20px;

  float: left;
}

.hot-posts h3 {
  margin-bottom: 10px;
}

.post-item {

  margin-bottom: 20px;
  display: flex; /* 使用Flex布局 */
  align-items: center; /* 垂直居中对齐 */
}

.post-index {
  font-weight: bold;
  color: #333;
  margin-right: 10px;
}


.post-title {
   overflow: hidden; /* 隐藏超出的内容 */
   text-overflow: ellipsis; /* 显示省略号(...)代替被隐藏的文本 */
   white-space: nowrap; /* 防止文本换行 */
   max-width: 60%; /* 可选：限制标题的最大宽度 */
   flex-grow: 1; /* 标题区域尽可能占据空间 */
 }

.post-popularity {
  color: red;
  margin-left: auto; /* 自动边缘，将元素推向右侧 */
  margin-right: 13px;
}

.post-text{
  overflow: hidden; /* 隐藏超出的内容 */
  text-overflow: ellipsis; /* 显示省略号(...)代替被隐藏的文本 */
  white-space: nowrap; /* 防止文本换行 */
  max-width: 90%; /* 可选：限制标题的最大宽度 */
  flex-grow: 1; /* 标题区域尽可能占据空间 */
}


.liked {
  fill: red;
}
.editor-container{
  width: 100%;
  height: 40vh;
  overflow: auto;


}
</style>
